﻿/*!	r_render_obj_def_vertex.cpp
	@brief	レンダリングオブジェクト頂点定義
Copyright (c) 2010 Yuya Yamaguchi

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "r_render_obj_def_vertex.h"

#include "../draw/r_draw_def.h"
#include "../draw/r_draw_inputlayout_desc.h"
#include "../draw/r_draw_inputlayout.h"
#include "../draw/r_draw_vertexbuffer.h"
#include "../draw/r_draw_indexbuffer.h"
#include "../draw/r_draw_vertexshader.h"
#include "../draw/r_draw_context.h"

#include "../stream/r_stream_default.h"

#include "../util/r_util_offsetcast.h"
#include <algorithm>

// >>>>>>>>>> RTTI >>>>>>>>>>
#include "../rtti/r_rtti_reflection_implement.h"
namespace r{
	namespace render{
RRTTI_REFLECTION_IMPLEMENT ( r::render::ObjDefVertex, r::rtti::ClassBase )
// <<<<<<<<<< RTTI <<<<<<<<<<

		// 頂点定義用ダミーシェーダファイルパス
		static const r_cstr	defaultShaderFileName = _RST( "data\\win32_dx11\\render_def.hlsl" );

		ObjDefVertexElementUseMap* ObjDefVertex :: layoutMapList = NULL;
		r::draw::VertexShader* ObjDefVertex :: defVS = NULL;
		r_ui32 ObjDefVertex :: genCount = 0;

		ObjDefVertex :: ObjDefVertex( const ObjDefVertexElementUse& vertexUseFlag, r_ui32 vertexTotalCount, r_ui32 indexTotalCount, r_ui32 subelementTotalCount )
		: vertexCount( vertexTotalCount )
		, indexCount( indexTotalCount )
		, useFlag( vertexUseFlag )
		, vertexLayout( NULL )
		, vertexBuffer( NULL )
		, indexBuffer( NULL )
		, strideSize( 0 )
		, colorOffset( 0 )
		, normalOffset( 0 )
		, uvOffset( 0 )
		, skin4Offset( 0 )
		{
			if( !layoutMapList ){
				layoutMapList = new ObjDefVertexElementUseMap;
			}
			++genCount;
			// 必要なストライドを計算する
			strideSize = sizeof( ObjDefVertexPos );
			if( useFlag.useNormal ){
				normalOffset = strideSize;
				strideSize += sizeof( ObjDefVertexNormal );
			}
			if( useFlag.useColor ){
				colorOffset = strideSize;
				strideSize += sizeof( ObjDefVertexColor );
			}
			if( useFlag.useUV ){
				uvOffset = strideSize;
				strideSize += sizeof( ObjDefVertexUV );
			}
			if( useFlag.useSkin4 ){
				skin4Offset = strideSize;
				strideSize += sizeof( ObjDefVertexSkin4 );
			}
			vertexBuffer = r::draw::VertexBuffer::create( strideSize, vertexCount );
			if( indexTotalCount > 0 ){
				indexBuffer = r::draw::IndexBuffer::create( indexCount );
			}
			if( subelementTotalCount < 1 ){
				subelementTotalCount = 1;
			}
			subelement.reserve( subelementTotalCount );
			subelement.resize( subelementTotalCount );
			subelement[0].fromIndex = 0;
			subelement[0].useIndexCount = indexCount;
			// 未登録レイアウトの場合は作成と登録を行う
			ObjDefVertexElementUseMap::iterator itLayout = layoutMapList->find( vertexUseFlag );
			if( itLayout == layoutMapList->end() ){
				const r_ui32 fakeStreamIndex = 15;
				r::draw::InputLayoutDesc layoutdesc;
				layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "POSITION" ), r::draw::InputLayoutFormat_FVec3, 0 ) );
				if( useFlag.useNormal ){
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "NORMAL" ), r::draw::InputLayoutFormat_FVec3, normalOffset ) );
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "TANGENT" ), r::draw::InputLayoutFormat_FVec3, normalOffset + sizeof( r::math::Vector3D ) ) );
				}else{
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "NORMAL" ), r::draw::InputLayoutFormat_FVec3, 0, 0, fakeStreamIndex ) );
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "TANGENT" ), r::draw::InputLayoutFormat_FVec3, 0, 0, fakeStreamIndex ) );
				}
				if( useFlag.useColor ){
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "COLOR" ), r::draw::InputLayoutFormat_UNorm4, colorOffset ) );
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "COLOR" ), r::draw::InputLayoutFormat_UNorm4, colorOffset + sizeof( r::math::ColorRGBi ), 1 ) );
				}else{
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "COLOR" ), r::draw::InputLayoutFormat_UNorm4, 0, 0, fakeStreamIndex ) );
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "COLOR" ), r::draw::InputLayoutFormat_UNorm4, 0, 1, fakeStreamIndex ) );
				}
				if( useFlag.useUV ){
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "TEXCOORD" ), r::draw::InputLayoutFormat_FVec2, uvOffset ) );
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "TEXCOORD" ), r::draw::InputLayoutFormat_FVec2, uvOffset + sizeof( r::math::Vector2D ), 1 ) );
				}else{
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "TEXCOORD" ), r::draw::InputLayoutFormat_FVec2, 0, 0, fakeStreamIndex ) );
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "TEXCOORD" ), r::draw::InputLayoutFormat_FVec2, 0, 1, fakeStreamIndex ) );
				}
				if( useFlag.useSkin4 ){
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "SKIN_WEIGHT" ), r::draw::InputLayoutFormat_FVec3, skin4Offset ) );
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "SKIN_INDEX" ), r::draw::InputLayoutFormat_UByte4, skin4Offset + sizeof( r::math::Vector3D ) ) );
				}else{
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "SKIN_WEIGHT" ), r::draw::InputLayoutFormat_FVec3, 0, 0, fakeStreamIndex ) );
					layoutdesc.add( r::draw::InputLayoutDescAttr( _RST ( "SKIN_INDEX" ), r::draw::InputLayoutFormat_UByte4, 0, 0, fakeStreamIndex ) );
				}
				// デフォルトシェーダが初期化されていなければ
				if( defVS == NULL ){
					r::stream::ReaderDefault tstream ( defaultShaderFileName );
					void* tmp = r::render::AllocatorData()()->malloc( tstream.getSize() + 1 );
					tstream.read ( tmp );
					defVS = r::draw::VertexShader::create( tmp, tstream.getSize(), _RST ( "DefVShader" ), _RST ( "render_def.hlsl" ) );
					r::render::AllocatorData()()->free( tmp );
				}
				vertexLayout = r::draw::InputLayout::create( layoutdesc, defVS );
				ObjDefVertexElementUsePair pair( useFlag, vertexLayout );
				layoutMapList->insert( pair );
			}else{
				vertexLayout = (*itLayout).second;
			}
		}

		ObjDefVertex :: ~ObjDefVertex( void )
		{
			--genCount;
			vertexBuffer->destroy();
			indexBuffer->destroy();
			if( genCount == 0 ){
				defVS->destroy();
				defVS = NULL;
				// 全てのレイアウト情報を破棄する
				std::for_each( layoutMapList->begin(), layoutMapList->end(), [&](ObjDefVertexElementUsePair it){ it.second->destroy(); } );
				layoutMapList->clear();
				delete layoutMapList;
				layoutMapList = NULL;
			}
		}

		r_bool ObjDefVertex :: mapVertex( void )
		{
			return vertexBuffer->map();
		}

		void ObjDefVertex :: unmapVertex( void )
		{
			vertexBuffer->unMap();
		}

		void ObjDefVertex :: setPosition( r_ui32 index, const r::math::Vector3D& pos )
		{
			ObjDefVertexPos* buff = r::util::offsetCast<ObjDefVertexPos*>( vertexBuffer->getBufferAddr(), index * strideSize );
			buff->pos = pos;
		}

		void ObjDefVertex :: setNormal( r_ui32 index, const r::math::Vector3D& normal )
		{
			ObjDefVertexNormal* buff = r::util::offsetCast<ObjDefVertexNormal*>( vertexBuffer->getBufferAddr(), index * strideSize + normalOffset );
			buff->normal = normal;
		}

		void ObjDefVertex :: setTangent( r_ui32 index, const r::math::Vector3D& tangent )
		{
			ObjDefVertexNormal* buff = r::util::offsetCast<ObjDefVertexNormal*>( vertexBuffer->getBufferAddr(), index * strideSize + normalOffset );
			buff->tangent = tangent;
		}

		void ObjDefVertex :: setColor0( r_ui32 index, const r::math::ColorRGBi& color )
		{
			ObjDefVertexColor* buff = r::util::offsetCast<ObjDefVertexColor*>( vertexBuffer->getBufferAddr(), index * strideSize + colorOffset );
			buff->color0 = color;
		}

		void ObjDefVertex :: setColor1( r_ui32 index, const r::math::ColorRGBi& color )
		{
			ObjDefVertexColor* buff = r::util::offsetCast<ObjDefVertexColor*>( vertexBuffer->getBufferAddr(), index * strideSize + colorOffset );
			buff->color1 = color;
		}

		void ObjDefVertex :: setUV0( r_ui32 index, const r::math::Vector2D& uv )
		{
			ObjDefVertexUV* buff = r::util::offsetCast<ObjDefVertexUV*>( vertexBuffer->getBufferAddr(), index * strideSize + uvOffset );
			buff->uv0 = uv;
		}

		void ObjDefVertex :: setUV1( r_ui32 index, const r::math::Vector2D& uv )
		{
			ObjDefVertexUV* buff = r::util::offsetCast<ObjDefVertexUV*>( vertexBuffer->getBufferAddr(), index * strideSize + uvOffset );
			buff->uv1 = uv;
		}

		void ObjDefVertex :: setSkin4( r_ui32 index, r_ui32 i0, r_ui32 i1, r_ui32 i2, r_ui32 i3, r_f32 w0, r_f32 w1, r_f32 w2 )
		{
			ObjDefVertexSkin4* buff = r::util::offsetCast<ObjDefVertexSkin4*>( vertexBuffer->getBufferAddr(), index * strideSize + skin4Offset );
			buff->index[0] = i0;
			buff->index[1] = i1;
			buff->index[2] = i2;
			buff->index[3] = i3;
			buff->weight[0] = w0;
			buff->weight[1] = w1;
			buff->weight[2] = w2;
		}

		r_bool ObjDefVertex :: mapIndex( void )
		{
			return indexBuffer->map();
		}

		void ObjDefVertex :: unmapIndex( void )
		{
			indexBuffer->unMap();
		}

		void ObjDefVertex :: setIndex( r_ui32 index, r_ui32 num )
		{
			indexBuffer->setIndex( index, num );
		}

		void ObjDefVertex :: setVertexAll( const void* allVertex )
		{
			vertexBuffer->setVertex( allVertex );
		}

		void ObjDefVertex :: setIndexAll( const r_ui16* allIndex )
		{
			indexBuffer->setIndex( allIndex );
		}
		void ObjDefVertex :: setIndexAll( const r_ui32* allIndex )
		{
			indexBuffer->setIndex( allIndex );
		}

		void ObjDefVertex :: setSubElementIndexInfo( r_ui32 from, r_ui32 count, r_ui32 index )
		{
			if( subelement.size() <= index ){
				return;
			}
			subelement[index].fromIndex = from;
			subelement[index].useIndexCount = count;
		}

		ObjDefVertexElementUse ObjDefVertex :: getVertexUseElement( void )const
		{
			return useFlag;
		}


		r_ui32 ObjDefVertex :: getVertexCount( void )const
		{
			return vertexCount;
		}

		r_ui32 ObjDefVertex :: getIndexCount( void )const
		{
			return indexCount;
		}

		r_ui32 ObjDefVertex :: getSubElementCount( void )const
		{
			return subelement.size();
		}

		r_bool ObjDefVertex :: getSubElementIndexInfo( r_ui32& from, r_ui32& count, r_ui32 index )const
		{
			if( subelement.size() <= index ){
				return false;
			}
			from = subelement[index].fromIndex;
			count = subelement[index].useIndexCount;
			return true;
		}
	

		const r::draw::InputLayout* ObjDefVertex :: getInputLayout( void )const
		{
			return vertexLayout;
		}

		void ObjDefVertex :: drawSubElementBegin( r::draw::Context* context )
		{
			context->IA_SetInputLayout( vertexLayout );
			context->IA_SetVertexBuffer( 0, vertexBuffer );
			if( indexCount > 0 ){
				context->IA_SetIndexBuffer( indexBuffer );
			}
		}

		void ObjDefVertex :: drawSubElement( r::draw::Context* context, r_ui32 index )
		{
			if( subelement.size() <= index ){
				return;
			}
			if( indexCount > 0 ){
				context->drawIndex( subelement[index].useIndexCount, subelement[index].fromIndex );
			}else{
				context->draw( subelement[index].useIndexCount, subelement[index].fromIndex );
			}
		}

		void ObjDefVertex :: drawSubElementEnd( r::draw::Context* context )
		{
			// 今は何もしない
		}
	}
}



